package controller;

import pojo.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService us=new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("GBK");
        resp.setCharacterEncoding("GBK");
        String uname = req.getParameter("uname");
        String upwd = req.getParameter("upwd");
        PrintWriter pw = resp.getWriter();
        if(uname!=null && upwd!=null) {
            User u=us.login(uname, upwd);
            if(u!=null) {
                HttpSession session = req.getSession();
                session.setAttribute("user",uname);
                resp.sendRedirect("http://localhost:8080/_1_Environment_war_exploded/success.jsp");//重定向

                pw.print("恭喜你！"+u.getUsername()+"登录成功！");
            }else {
                pw.print("您输入的用户名或密码错误！");
            }
        }else {
            pw.print("您输入的用户名或密码为空！");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
//        String name = req.getParameter("name");
//        String password = req.getParameter("password");
//        if("123456".equals(password))
//            req.setAttribute("result","登录成功，欢迎"+name);
//        else
//            req.setAttribute("result","登录失败，密码错误");
//        req.getRequestDispatcher("/login.jsp").forward(req,resp);
        doGet(req, resp);
    }
}
